import styles from "@styles/active/activeadd.module.less";

import moment from "moment";
import React, { useState, useEffect } from "react";
import { withRouter } from "react-router-dom";
import {
  Collapse,
  Button,
  Steps,
  Form,
  Input,
  Cascader,
  DatePicker,
  Upload,
  Modal,
  Space,
  message,
} from "antd";
import {
  DeleteOutlined,
  PlusOutlined,
  CaretRightOutlined,
} from "@ant-design/icons";
import ImgCrop from "antd-img-crop";
import {
  layout,
  acttype,
  dateFormat,
  setdateDates,
  disabledDate,
  dateFormatTime,
  handleBeforeUpload,
  signupFormlistprojrctName,
  deleteArrayTerm,
  cloneArray,
  isnullObj,
  deepCopy,
  mergeObj,
} from "@actions/data";
import Http from "@utils/api";
import SignUp from "@pages/active/children/signup";
import Vote from "@pages/active/children/vote";
import RobTickets from "@pages/active/children/robTickets";
import SignIn from "@pages/active/children/everyoneExpose";
import LuckyDraw from "@pages/active/children/luckyDraw";

const { Step } = Steps;
const { Panel } = Collapse;
const { RangePicker } = DatePicker;

function CreateEditActivity({ history, location }) {
  const {
    state: { activityBasicId },
  } = location;
  const acttypes = cloneArray(acttype);
  const [formCreate] = Form.useForm(); // 表单 — 基本信息
  const [formSignUp] = Form.useForm(); // 表单 — 报名
  const [formVote] = Form.useForm(); // 表单 - 投票
  const [formRobTickets] = Form.useForm(); // 表单 — 门票
  const [formSignIn] = Form.useForm(); // 表单 — 签到
  const [formLuckyDraw] = Form.useForm(); // 表单 — 抽奖

  const [previewVisible, setPreviewVisible] = useState(false);
  const [previewImage, setPreviewImage] = useState("");
  const [province, setProvince] = useState([]);
  const [cascaderCity, setCascaderCity] = useState(province);
  const [fileListActivity, setFileListActivity] = useState([]);
  const [fileListThumbnail, setFileListThumbnail] = useState([]);
  const [iscount, setIscount] = useState(false);
  const [actType, setActType] = useState([]);
  const [henderType, setHenderType] = useState([]);

  useEffect(() => {
    if (activityBasicId) {
      Http.queryByUpdate({
        activityBasicId: activityBasicId,
      }).then(({ data }) => {
        data.area = [data.provinceCode, data.cityCode];
        data.rangepicker = [moment(data.startDate), moment(data.endDate)];
        setFileListActivity([
          {
            uid: data.pictureKey,
            name: data.pictureKey,
            status: "done",
            url: data.pictureUrl,
          },
        ]);
        setFileListThumbnail([
          {
            uid: data.thumbnailPictureKey,
            name: data.thumbnailPictureKey,
            status: "done",
            url: data.thumbnailPictureUrl,
          },
        ]);
        data.scheduleVOS = (data.scheduleVOS || []).map((item) => {
          item.scheduleDate = moment(item.scheduleDate);
          return item;
        });
        formCreate.setFieldsValue(data);

        (data.activityVOS || []).map(item => {
          switch(item.activityType) {
            case 1: formSignUp.setFieldsValue(item); break;
            case 2: formVote.setFieldsValue(item); break;
            case 3: formRobTickets.setFieldsValue(item); break;
            case 4: formSignIn.setFieldsValue(item); break;
            case 5: formLuckyDraw.setFieldsValue(item); break;
            default: message.warn('未知'); break;
          }
          return true;
        });
        getprovince(true, data.provinceCode);
      });
    } else {
      formCreate.setFieldsValue({
        activityBasicId: "",
        activityName: "",
        area: [],
        activitySite: "",
        activityOrganizers: "",
        activityContent: "",
        activityVOS: [],
        scheduleVOS: [],
        provinceCode: "",
        cityCode: "",
        rangepicker: [],
        startDate: "",
        endDate: "",
        isSignUp: false,
        isVote: false,
        isRobTickets: false,
        isSignIn: false,
        isLuckyDraw: false,
      });
      getprovince();
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [activityBasicId]);

  // 上传图片返回按钮
  const handleCancel = () => setPreviewVisible(false);

  // 图片上传 - 图片改变
  const onChangeActivity = ({ file: { status, response }, file }) => {
    if (status !== "uploading") setFileListActivity([]);
    if (status === "done") {
      message.success("上传成功");
      setFileListActivity([
        {
          uid: file.uid,
          name: response.data.imgKey,
          status: status,
          url: response.data.imgUrl,
        },
      ]);
      formCreate.setFieldsValue({
        pictureKey: response.data.imgKey,
        pictureUrl: response.data.imgUrl,
      });
    } else if (status === "error") {
      message.error("上传失败！");
    }
  };
  const onChangeThumbnail = ({ file: { status, response }, file }) => {
    if (status !== "uploading") setFileListThumbnail([]);
    if (status === "done") {
      message.success("上传成功");
      setFileListThumbnail([
        {
          uid: file.uid,
          name: response.data.imgKey,
          status: status,
          url: response.data.imgUrl,
        },
      ]);
      formCreate.setFieldsValue({
        thumbnailPictureKey: response.data.imgKey,
        thumbnailPictureUrl: response.data.imgUrl,
      });
    } else if (status === "error") {
      message.error("上传失败！");
    }
  };

  // 图片上传 - 图片预览
  const onPreview = async (file) => {
    let src = file.url;
    if (!src) {
      src = await new Promise((resolve) => {
        const reader = new FileReader();
        reader.readAsDataURL(file.originFileObj);
        reader.onload = () => resolve(reader.result);
      });
    }
    setPreviewImage(src);
    setPreviewVisible(true);
  };

  // 省市改变
  const cascaderChange = (value) => {
    formCreate.setFieldsValue({
      provinceCode: value[0] || 0,
      cityCode: value[1] || 0,
    });
  };

  // 确定省级
  const getprovince = (value = false, provincesCode) => {
    Http.queryAddressForFourLinkage({
      addressLevel: 1,
    }).then(({ data }) => {
      let provinces = data.map(({ addressCode, addressName }) => ({
        value: addressCode,
        label: addressName,
        isLeaf: false,
      }));

      setProvince(provinces);
      if (value) {
        let currprovinces = provinces.filter(
          (item) => item.value === provincesCode
        );
        loadData(currprovinces);
      }
    });
  };

  // 确定市级
  const loadData = (selectedOptions) => {
    if (!selectedOptions) return false;
    const targetOption = selectedOptions[selectedOptions.length - 1];
    Http.queryAddressForFourLinkage({
      addressLevel: 2,
      parentId: targetOption.value,
    }).then(({ data }) => {
      let provinces = data.map(({ addressCode, addressName }) => ({
        value: addressCode,
        label: addressName,
      }));
      targetOption.children = provinces;
      setCascaderCity([...cascaderCity]);
    });
  };

  // 活动时间选择
  const rangepickerChange = (value, valueStr) => {
    formCreate.setFieldsValue({
      startDate: valueStr[0],
      endDate: valueStr[1],
    });
  };

  // 上一步 下一步
  const prevStepProcess = () => setIscount(false);
  const nextStepProcess = () => {
    // setIscount(true);
    formCreate
      .validateFields()
      .then(() => {
        setIscount(true);
      })
      .catch(() => {
        message.warning("请填写必填项");
      });
  };

  // 活动类型选择
  const selectActivityType = (value) => {
    value.status = !value.status;
    let selValue = deleteArrayTerm(actType, value.id);
    setActType(selValue);
    let pushObj = {
      [value.key]: value.status,
    };
    formCreate.setFieldsValue(pushObj);
    formSignUp.setFieldsValue({
      activityType: value.id,
    });
  };

  // 创建的活动 - 展开/收起
  const changehender = (value) => setHenderType([...value]);

  const resetAllForm = () => {
    const { isSignUp, isVote, isRobTickets, isSignIn, isLuckyDraw } = {
      ...formCreate.getFieldValue(),
    };
    if (!isSignUp) formSignUp.resetFields();
    if (!isVote) formVote.resetFields();
    if (!isRobTickets) formRobTickets.resetFields();
    if (!isSignIn) formSignIn.resetFields();
    if (!isLuckyDraw) formLuckyDraw.resetFields();
    if (!(isSignUp || isVote || isRobTickets || isSignIn || isLuckyDraw)) {
      message.warn("至少选择一种活动类型");
      return false;
    }
  };

  const onFinishAddActivity = (value) => {
    let arrForm = resetAllForm();
    let formSignUpData = { ...formSignUp.getFieldValue() };
    let formVoteData = { ...formVote.getFieldValue() };
    let formRobTicketsData = { ...formRobTickets.getFieldValue() };
    let formSignInData = { ...formSignIn.getFieldValue() };
    let formLuckyDrawData = { ...formLuckyDraw.getFieldValue() };

    if (!isnullObj(formSignUpData)) {
      if (
        formSignUpData.optionalEntryForms &&
        formSignUpData.optionalEntryForms.length > 0
      ) {
        formSignUpData.optionalEntryForms = formSignUpData.optionalEntryForms.map(
          (v) => {
            return mergeObj(v, signupFormlistprojrctName);
          }
        );
      }
      delete formSignUpData.rangepicker;
      console.warn("报名信息: ", formSignUpData);
    }
    if (!isnullObj(formVoteData)) {
      console.warn("投票信息: ", formVote.getFieldValue());
    }
    if (!isnullObj(formRobTicketsData)) {
      console.warn("门票信息: ", formRobTickets.getFieldValue());
    }
    if (!isnullObj(formSignInData)) {
      console.warn("签到信息: ", formSignIn.getFieldValue());
    }
    if (!isnullObj(formLuckyDrawData)) {
      console.warn("抽奖信息: ", formLuckyDraw.getFieldValue());
    }

    debugger
    let pushObj = {
      activityVOS: [
        formSignUpData,
        formVoteData,
        formRobTicketsData,
        formSignInData,
        formLuckyDrawData,
      ].filter((x) => !isnullObj(x)),
    };
    formCreate.setFieldsValue(pushObj);

    console.warn(formCreate.getFieldValue());
    let formCreateData = deepCopy(formCreate.getFieldValue());
    delete formCreateData.rangepicker;
    delete formCreateData.isDraft;
    delete formCreateData.isDelete;
    formCreateData.scheduleVOS = (formCreateData.scheduleVOS || []).map(
      (item) => {
        item.scheduleDate = setdateDates(item.scheduleDate);
        return item;
      }
    );

    console.warn("基本信息: ", formCreateData);
    if (arrForm === false) return false;
    if (value === "draft") saveDrafts({ ...formCreateData });
    else formSubmit({ ...formCreateData });
  };

  // 发布
  const formSubmit = (value) => {
    Http.addActivity({ ...value }).then(({ code }) => {
      console.warn("表单成功返回值：", code);
      if (code === 200) {
        history.push({ pathname: "/createActivity", state: {} });
      }
    });
  };

  // 保存草稿
  const saveDrafts = (value) => {
    Http.saveDrafts({ ...value }).then((res) => {
      if (res.code === 200) {
        message.success(res.message);
        history.push({ pathname: "/createActivity", state: {} });
      }
    });
  };

  return (
    <article className={styles.activeadd}>
      <section className={styles.progressbox}>
        <h1>创建活动</h1>
        <Steps
          current={iscount ? 2 : 1}
          progressDot
          size="small"
          className={styles.progressstyle}
        >
          <Step title="基本信息" />
          <Step />
          <Step title="活动信息" />
        </Steps>
      </section>
      <section className={styles.formInfo}>
        <pre
          className={[styles.basicInfo, iscount ? styles.none : ""].join(" ")}
        >
          <Form
            {...layout}
            layout="vertical"
            form={formCreate}
            onFinish={onFinishAddActivity}
          >
            <h5>请填写活动的基本信息</h5>
            <main className={styles.basicInfo}>
              <aside>
                <Form.Item
                  label="活动名称"
                  name="activityName"
                  rules={[
                    {
                      required: true,
                      message: "请输入活动名称",
                      whitespace: true,
                    },
                  ]}
                >
                  <Input placeholder="请输入活动名称" />
                </Form.Item>
                <Form.Item
                  label="地区选择"
                  name="area"
                  rules={[
                    {
                      required: true,
                      message: "请选择活动所属地区",
                    },
                  ]}
                >
                  <Cascader
                    options={province}
                    onChange={cascaderChange}
                    loadData={loadData}
                    placeholder="请选择活动所属地区"
                  />
                </Form.Item>
              </aside>
              <aside>
                <Form.Item
                  name="rangepicker"
                  label="活动时间"
                  rules={[{ required: true, message: "请选择活动时间" }]}
                >
                  <RangePicker
                    showTime
                    disabledDate={disabledDate}
                    format={dateFormatTime}
                    placeholder={["开始时间", "结束时间"]}
                    onChange={rangepickerChange}
                  />
                </Form.Item>
                <Form.Item
                  label="活动地点"
                  name="activitySite"
                  rules={[
                    {
                      required: true,
                      message: "请输入活动地点",
                      whitespace: true,
                    },
                  ]}
                >
                  <Input placeholder="请输入活动地点" />
                </Form.Item>
              </aside>
              <aside>
                <Form.Item
                  label="活动主办方"
                  name="activityOrganizers"
                  rules={[
                    {
                      required: true,
                      message: "请输入活动主办方",
                      whitespace: true,
                    },
                  ]}
                >
                  <Input placeholder="请输入活动主办方" />
                </Form.Item>
                <Form.Item
                  label="活动内容"
                  name="activityContent"
                  rules={[
                    {
                      required: true,
                      message: "请输入活动内容",
                      whitespace: true,
                    },
                  ]}
                >
                  <Input.TextArea placeholder="请输入活动内容" />
                </Form.Item>
              </aside>
              <aside>
                <Form.Item
                  label="活动图"
                  name="pictureUrl"
                  extra="推荐尺寸：1035*261"
                  rules={[{ required: true, message: "请选择活动图" }]}
                >
                  <ImgCrop {...{ aspect: 1035 / 261 }}>
                    <Upload
                      action="/campus/campusweb/upload/pictureUpload"
                      listType="picture-card"
                      name="multipartFile"
                      fileList={fileListActivity}
                      onChange={onChangeActivity}
                      onPreview={onPreview}
                      beforeUpload={handleBeforeUpload}
                      className={styles.uploadImg}
                    >
                      {fileListActivity.length < 1 && (
                        <div>
                          <p>+</p>
                          <p>添加图片</p>
                        </div>
                      )}
                    </Upload>
                  </ImgCrop>
                </Form.Item>
                <Form.Item
                  label="缩略图"
                  name="thumbnailPictureUrl"
                  extra="推荐尺寸：168*216"
                  rules={[{ required: true, message: "请选择缩略图" }]}
                >
                  {
                    <ImgCrop {...{ aspect: 168 / 216 }}>
                      <Upload
                        action="/campus/campusweb/upload/pictureUploadCompression"
                        listType="picture-card"
                        name="multipartFile"
                        fileList={fileListThumbnail}
                        onChange={onChangeThumbnail}
                        onPreview={onPreview}
                        className={styles.uploadImg1}
                      >
                        {fileListThumbnail.length < 1 && (
                          <div>
                            <p>+</p>
                            <p>添加图片</p>
                          </div>
                        )}
                      </Upload>
                    </ImgCrop>
                  }
                </Form.Item>
                <Modal
                  visible={previewVisible}
                  footer={null}
                  onCancel={handleCancel}
                  title="预览"
                >
                  <img
                    alt="example"
                    style={{ width: "100%" }}
                    src={previewImage}
                  />
                </Modal>
              </aside>
            </main>
            <h5>
              请编辑活动日程规划 <span>（可添加多条）</span>
            </h5>
            <main className={styles.schedule}>
              <aside className={styles.scheduleBox}>
                <Form.List name="scheduleVOS">
                  {(fields, { add, remove }) => (
                    <>
                      {fields.map((field) => (
                        <Space
                          key={field.key}
                          align="baseline"
                          className={styles.scheduleVOS}
                        >
                          <Form.Item
                            {...field}
                            wrapperCol={{ span: 24 }}
                            name={[field.name, "scheduleName"]}
                            fieldKey={[field.fieldKey, "scheduleName"]}
                            rules={[
                              { required: true, message: "请输入日程名称" },
                            ]}
                          >
                            <Input placeholder="请输入日程名称" />
                          </Form.Item>
                          <Form.Item
                            {...field}
                            wrapperCol={{ span: 24 }}
                            name={[field.name, "scheduleDate"]}
                            fieldKey={[field.fieldKey, "scheduleDate"]}
                            rules={[
                              { required: true, message: "请选择日程时间" },
                            ]}
                          >
                            <DatePicker
                              placeholder="请选择日程时间"
                              disabledDate={disabledDate}
                              format={dateFormat}
                            />
                          </Form.Item>
                          <DeleteOutlined onClick={() => remove(field.name)} />
                        </Space>
                      ))}
                      <Form.Item wrapperCol={{ span: 24 }}>
                        <Button
                          type="dashed"
                          onClick={() => add()}
                          block
                          icon={<PlusOutlined />}
                        >
                          添加
                        </Button>
                      </Form.Item>
                    </>
                  )}
                </Form.List>
              </aside>
            </main>
          </Form>
        </pre>
        <pre className={[styles.actInfo, iscount ? "" : styles.none].join(" ")}>
          <h5>
            选择你想要创建的活动<span>（可多选）</span>
          </h5>
          <nav className={styles.selectActtype}>
            {acttypes.map((item) => (
              <li
                key={item.id}
                onClick={() => selectActivityType(item)}
                className={
                  actType.includes(item.id) ? styles.actTypeActive : ""
                }
              >
                {item.name}
              </li>
            ))}
          </nav>
          <Collapse
            collapsible="header"
            expandIconPosition="right"
            bordered={false}
            onChange={changehender}
            expandIcon={({ isActive }) => (
              <CaretRightOutlined rotate={isActive ? -90 : 90} />
            )}
            className={styles.customCollapse}
            defaultActiveKey={["1", "2", "3", "4", "5"]}
          >
            {actType.includes(1) ? (
              <Panel
                header="报名"
                key="1"
                extra={henderType.includes("1") ? `收起` : `展开`}
                className={styles.customPanel}
                forceRender
              >
                <SignUp formSignUp={formSignUp} formCreate={formCreate} />
              </Panel>
            ) : (
              <></>
            )}
            {actType.includes(2) ? (
              <Panel
                header="投票"
                key="2"
                extra={henderType.includes("2") ? `收起` : `展开`}
                className={styles.customPanel}
                forceRender
              >
                <Vote formVote={formVote} />
              </Panel>
            ) : (
              <></>
            )}
            {actType.includes(3) ? (
              <Panel
                header="门票"
                key="3"
                extra={henderType.includes("3") ? `收起` : `展开`}
                className={styles.customPanel}
              >
                <RobTickets formRobTickets={formRobTickets}></RobTickets>
              </Panel>
            ) : (
              <></>
            )}
            {actType.includes(4) ? (
              <Panel
                header="签到"
                key="4"
                extra={henderType.includes("4") ? `收起` : `展开`}
                className={styles.customPanel}
              >
                <SignIn formSignIn={formSignIn}></SignIn>
              </Panel>
            ) : (
              <></>
            )}
            {actType.includes(5) ? (
              <Panel
                header="抽奖"
                key="5"
                extra={henderType.includes("5") ? `收起` : `展开`}
                className={styles.customPanel}
              >
                <LuckyDraw formLuckyDraw={formLuckyDraw}></LuckyDraw>
              </Panel>
            ) : (
              <></>
            )}
          </Collapse>
        </pre>
        <aside className={styles.allButton}>
          {iscount ? (
            <>
              <Button
                htmlType="submit"
                type="primary"
                onClick={onFinishAddActivity}
              >
                发布
              </Button>
              <Button htmlType="button" onClick={prevStepProcess}>
                上一步
              </Button>
            </>
          ) : (
            <>
              <Button
                htmlType="button"
                type="primary"
                onClick={nextStepProcess}
              >
                下一步
              </Button>
            </>
          )}
          <Button htmlType="button">预览</Button>
          <Button
            htmlType="button"
            onClick={() => onFinishAddActivity("draft")}
          >
            保存草稿
          </Button>
        </aside>
      </section>
    </article>
  );
}

export default withRouter(CreateEditActivity);
